<template>
  <div style="width: 100%;height: 100%;display: flex">
    <div class="left_box">
      <div class="code_box">
        <ace-editor  style="width: 100%;height: 100%" :html-text-value="htmlStr" :ts-text-value="tsStr"></ace-editor>
      </div>
    </div>
    <div id="load4490_box">
      <div class="popup_box">
        <div class="inner_content_common">
          <div class="single_item">
            <div class="single_item_title">缓冲点：</div>
            <div style="margin-right: 10px;">
              <el-button @click="createGeometry('Point')">创建点</el-button>
              <el-button @click="startAnalysis('Point')">分析</el-button>
            </div>
          </div>
          <div class="single_item">
            <div class="single_item_title">缓冲线：</div>
            <div style="margin-right: 10px;">
              <el-button @click="createGeometry('Polyline')">创建线</el-button>
              <el-button @click="startAnalysis('Polyline')">分析</el-button>
            </div>
          </div>
          <div class="single_item">
            <div class="single_item_title">缓冲面：</div>
            <div style="margin-right: 10px;">
              <el-button @click="createGeometry('Polygon')">创建面</el-button>
              <el-button @click="startAnalysis('Polygon')">分析</el-button>
            </div>
          </div>
          <el-button style="margin-top: 10px;width: 100px;" @click="removeAnalysis">清除</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {initMap} from "@/widgets/modelExample_cesium/common/initMap";
import {loadTdtLayer} from "@/widgets/modelExample_cesium/common/loadLayers";
import bufferAnalysis from "@/widgets/modelExample_cesium/common/analysis/bufferAnalysis/bufferAnalysis";
import {onMounted, ref} from "vue";

import AceEditor from "@/components/aceEditor.vue";

const htmlStr=ref(`
<template>
  <div style="width: 100%;height: 100%;display: flex">
    <div id="load4490_box">
      <div class="popup_box">
        <div class="inner_content_common">
          <div class="single_item">
            <div class="single_item_title">缓冲点：</div>
            <div style="margin-right: 10px;">
              <el-button @click="createGeometry('Point')">创建点</el-button>
              <el-button @click="startAnalysis('Point')">分析</el-button>
            </div>
          </div>
          <div class="single_item">
            <div class="single_item_title">缓冲线：</div>
            <div style="margin-right: 10px;">
              <el-button @click="createGeometry('Polyline')">创建线</el-button>
              <el-button @click="startAnalysis('Polyline')">分析</el-button>
            </div>
          </div>
          <div class="single_item">
            <div class="single_item_title">缓冲面：</div>
            <div style="margin-right: 10px;">
              <el-button @click="createGeometry('Polygon')">创建面</el-button>
              <el-button @click="startAnalysis('Polygon')">分析</el-button>
            </div>
          </div>
          <el-button style="margin-top: 10px;width: 100px;" @click="removeAnalysis">清除</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {initMap} from "@/widgets/modelExample_cesium/common/initMap";
import {loadTdtLayer} from "@/widgets/modelExample_cesium/common/loadLayers";
import bufferAnalysis from "@/widgets/modelExample_cesium/common/analysis/bufferAnalysis/bufferAnalysis";
import {onMounted, ref} from "vue";


const cViewer = ref();
let bufferAna:any=null;

onMounted(() => {
  cViewer.value = initMap("load4490_box")
  loadTdtLayer(cViewer.value, 'c', false);
})


const createGeometry=(type:string)=>{
  let xoffset= document.body.clientWidth*0.4;
  if(!bufferAna){
    bufferAna=new bufferAnalysis(cViewer.value);
  }
  bufferAna.createGeometry(type,{
    popOffset:{x:xoffset,y:72}
  });
}

const startAnalysis=(type:string)=>{
  bufferAna.createBuffer(type,10000);
}

const removeAnalysis=()=>{
  bufferAna.clearBuffer();
}
<\/script>

<style lang="scss" scoped>
#load4490_box {
  width: 60%;
  height: 100%;
}

.popup_box {
  position: fixed;
  left: calc(40% + 100px);
  width: 240px;
  top: 100px;
  height: 60px;
  z-index: 10;
}

.inner_content_common {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  .single_item{
    border: 1px solid #40a9ff;
    border-radius: 5px;
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    align-items: center;
  }
  .single_item_title{
    margin: 10px;
    color: #ffffff;
  }
}
</style>

`);
const  tsStr=ref(`
   /**
 * 缓冲区分析
 */
import * as Cesium from 'cesium';
// @ts-ignore
import * as turf from '@turf/turf'
import Point from '../../Draw/Point';
import Polygon from '../../Draw/Polygon';
import Polyline from '../../Draw/Polyline';

class BufferAnalysis {
    _viewer: any;
    drawTool: any;
    entities: any;
    pointTool: any;
    polygonTool: any;
    polylineTool: any;

    constructor(viewer: any) {
        this._viewer = viewer;
        this.polylineTool = null;
        this.polygonTool = null;
        this.pointTool = null;
        this.entities = [];
    }

    /**
     * 开始绘制-点线面
     * @param type "Point" | "Polyline" | "Polygon"
     * @param options  {
     *   "Point" : { "iconImage":"图片的内容"  }
     *   "Polyline":{ "stroken":"线颜色","width":"线宽度" }
     *   "Polygon":{ fill:"填充颜色","opacity":"透明度","stroken":"线颜色","width":"线宽度" }
     *   "standard":{ "name":"军标名称","iconImage":"自定义的icon的内容" }  暂不支持
     *     "popOffset":{x:1,y:1}
     * }
     */
    createGeometry(type: string, options: any) {
        //重新绘制不用清掉数据
        // this.clearBuffer();
        if (type === "Point") {
            this.pointTool = new Point(this._viewer);
            this.pointTool.startDraw(false,{
                popOffset:options['popOffset'],
                iconImage:'无'
            });
        } else if (type === "Polyline") {
            this.polylineTool = new Polyline(this._viewer);
            this.polylineTool.startDraw(false,{popOffset:options['popOffset']});
        } else if (type === "Polygon") {
            this.polygonTool = new Polygon(this._viewer);
            this.polygonTool.startDraw(false,{popOffset:options['popOffset']});
        }
        // this.drawTool.startDraw(type, false, options)
    }

    /**
     * 创建缓冲区
     * @param type "Point" | "Polyline" | "Polygon"
     * @param bufferDistance
     */
    createBuffer(type: string, bufferDistance: number) {
        let drawTool=null;
        if (type === "Point") {
            drawTool=this.pointTool;
        } else if (type === "Polyline") {
            drawTool=this.polylineTool;
        } else if (type === "Polygon") {
            drawTool=this.polygonTool;
        }
        let geometry = drawTool.drawedPositions;
        if(type==="Polyline" || type==="Polygon"){
            geometry=geometry[0];
        }
        let jwdArr = innerFun.car3ToJwd(this._viewer,geometry);
        let degreesArray: any = null;
        if (type === "Point") {
            let turfPoint = turf.point(jwdArr[0]);
            let buffered = turf.buffer(turfPoint, bufferDistance, {units: 'meters'});
            let coordinates = buffered.geometry.coordinates;
            let points = coordinates[0];
            degreesArray = innerFun.pointsToDegreesArray(points);
        } else if (type === "Polyline") {
            let polylineF = turf.lineString(jwdArr);
            let buffered = turf.buffer(polylineF, bufferDistance, {units: 'meters'});
            let coordinates = buffered.geometry.coordinates;
            let points = coordinates[0];
            degreesArray = innerFun.pointsToDegreesArray(points);
        } else if (type === "Polygon") {
            if(jwdArr.length>0){
                jwdArr.push(jwdArr[0])
            }
            let polygonF = turf.polygon([jwdArr]);
            let buffered = turf.buffer(polygonF, bufferDistance, {units: 'meters'});
            let coordinates = buffered.geometry.coordinates;
            let points = coordinates[0];
            degreesArray = innerFun.pointsToDegreesArray(points);
        }
        let entity = this._viewer.entities.add({
            polygon: {
                hierarchy: new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArray(degreesArray)),
                material: Cesium.Color.RED.withAlpha(0.6),
                classificationType: Cesium.ClassificationType.BOTH
            },
        });

        this.entities.push(entity);
    }

    /**
     * 清除绘制和分析
     */
    clearBuffer() {
        if(this.pointTool){
            this.pointTool.clearDrawGraphic();
        }
        if(this.polylineTool){
            this.polylineTool.clearDrawGraphic();
        }
        if(this.polygonTool){
            this.polygonTool.clearDrawGraphic()
        }
        if (this.entities.length>0) {
            this.entities.forEach((item:any)=>{
                this._viewer.entities.remove(item);
            })
        }
    }


}

export default BufferAnalysis;
const innerFun = {
    car3ToJwd: function (viewer:any,Cartesian3Arr: any) {
        let arr = [];
        if (Cartesian3Arr.length > 0) {
            for (let i = 0; i < Cartesian3Arr.length; i++) {
                let cartographic = Cesium.Cartographic.fromCartesian(Cartesian3Arr[i], viewer.scene.globe.ellipsoid, new Cesium.Cartographic());
                let lng = Cesium.Math.toDegrees(cartographic.longitude);//经度
                let lat = Cesium.Math.toDegrees(cartographic.latitude);//纬度
                arr.push([lng, lat])
            }
        }
        return arr;
    },
    //格式转换
    pointsToDegreesArray(points: any) {
        let degreesArray: any = [];
        points.map((item: any) => {
            degreesArray.push(item[0]);
            degreesArray.push(item[1]);
        });
        return degreesArray;
    }
}

`);

const cViewer = ref();
let bufferAna:any=null;

onMounted(() => {
  cViewer.value = initMap("load4490_box")
  loadTdtLayer(cViewer.value, 'c', false);
})


const createGeometry=(type:string)=>{
  let xoffset= document.body.clientWidth*0.4;
  if(!bufferAna){
    bufferAna=new bufferAnalysis(cViewer.value);
  }
  bufferAna.createGeometry(type,{
    popOffset:{x:xoffset,y:72}
  });
}

const startAnalysis=(type:string)=>{
  bufferAna.createBuffer(type,10000);
}

const removeAnalysis=()=>{
  bufferAna.clearBuffer();
}
</script>

<style lang="scss" scoped>
.left_box {
  width: 40%;
  height: 100%;
  display: flex;
  flex-direction: row-reverse;

  .code_box {
    margin: 10px;
    width: calc(100% - 220px);
    height: calc(100% - 20px);
    //border:1px solid #00ff00;
    background-color: #ffffff;
    color: #000;
    overflow-x: hidden;
    overflow-y: auto;
  }
}

#load4490_box {
  width: 60%;
  height: 100%;
}

.popup_box {
  position: fixed;
  left: calc(40% + 100px);
  width: 240px;
  top: 100px;
  height: 60px;
  z-index: 10;
}

.inner_content_common {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  .single_item{
    border: 1px solid #40a9ff;
    border-radius: 5px;
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    align-items: center;
  }
  .single_item_title{
    margin: 10px;
    color: #ffffff;
  }
}
</style>
